﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yichat.MicroService.Interface;
using Yichat.MicroService.Model;

namespace Yichat.MicroService.ServiceInstance.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : Controller
    {
        private readonly ILogger<UsersController> _logger;
        private readonly IUserService _userService;
        private IConfiguration _configuration;

        public UsersController(ILogger<UsersController> logger,
            IUserService userService,
            IConfiguration configuration)
        {
            _logger = logger;
            _userService = userService;
            _configuration = configuration;
        }

        [Route("All")]
        public async Task<IEnumerable<User>> Get()
        {
            var ip = _configuration["ip"];
            var port = _configuration["port"];

            var host = $"{_configuration["Host"]}/api/cacheservice";
#if DEBUG
            host = $"{_configuration["Host"]}:44370";
#endif
            var url = $"{host}/cache/get?key=getusers";

            List<User> users = null;

            var output = await Common.Utils.InvokeApiAync(url);
            if (output.IsSuccessStatusCode
                && !string.IsNullOrEmpty(output.Payload))
            {
                users = JsonConvert.DeserializeObject<List<User>>(output.Payload);
            }
            else
            {
                users = _userService.GetUsers().Select(a => new User
                {
                    Id = a.Id,
                    Name = a.Name,
                    Role = $"{ip} {port}",
                }).ToList();

                url = $"{host}/cache/set?key=getusers&value={JsonConvert.SerializeObject(users)}";
                await Common.Utils.InvokeApiAync(url);
            }

            return users;
        }
    }
}
